package com.deyuanyun.pic.settings.service.prvlg.impl;

import com.deyuanyun.pic.settings.mapper.prvlg.dao.RoleDao;
import com.deyuanyun.pic.settings.support.cache.SessionCacheSupport;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.MapUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.settings.controller.dto.UserSessionVO;
import com.deyuanyun.pic.settings.domain.prvlg.Menu;
import com.deyuanyun.pic.settings.domain.prvlg.Role;
import com.deyuanyun.pic.settings.service.prvlg.RoleService;
import com.github.pagehelper.Page;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Service
public class RoleServiceImpl implements RoleService{
	static Logger logger= Logger.getLogger(RoleServiceImpl.class);

	@Resource
	private RoleDao roleDao;

	@Override
	public Page<HashMap<String, Object>> getMenus(HashMap<String, Object> map) {
		return roleDao.getMenus(map);
	}

	@Override
	public HashMap<String, Object> getOneMenu(HashMap<String, Object> map) {
		
		return roleDao.getOneMenu(map);
	}
	
	/*@Override
	public HashMap<String, Object> updateMenuState(HashMap<String, Object> map) {
		return roleDao.updateMenuState(map);
	}*/

	

	@Override
	public Map insertRole(HashMap  record )throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
	/*	Map<String,Object> praMap = new HashMap<String,Object>();
		praMap.put("roleName", record);*/
		Map map=new HashMap();
		String oRoleName = null;
		try {
			oRoleName = roleDao.getOneRole(record);
		} catch (Exception e) {
			logger.error("",e);
			map.put("err","角色名称或者编号已经存在");
			return map;
		}

		if(null != oRoleName ){
			map.put("err","角色名称或者编号已经存在");
			return map;
		}else {
			UserSessionVO sessionVO= SessionCacheSupport.getSessionVO();
			Role role=new Role();
			role.setCreateDate(new Date());
			role.setDeleted((short)0);
			role.setState((short)0);
			role.setCreateUser(sessionVO.getUsername());
			role.setName(record.get("ROLENAME").toString());
			role.setCode(null == record.get("ROLECODE") ? "" : record.get("ROLECODE").toString());
			role.setCreateRemark(null == record.get("REMARK")? "" : record.get("REMARK").toString());

			if (org.apache.commons.lang.StringUtils.isBlank(role.getName())||
					org.apache.commons.lang.StringUtils.isBlank(role.getCode())){
				map.put("err","名称或者编号不能为空");
				return map;
			}

			roleDao.insertSelective(role);
			return map;
		}
	}




	@Override
	public Page<HashMap<String, Object>> getRoles(HashMap<String, Object> map) {
		return roleDao.getRoles(map);
	}

	@Override
	public String getOneRole(HashMap<String, Object> map) {
		return roleDao.getOneRole(map);
	}

	@Override
	public Map updateState(HashMap param) {
		Map map=new HashMap();

		Object id=param.get("id");
		Object ids=param.get("idList");
		int n=0;
		if (id==null||"".equals(id)){
			if (ids==null){
				map.put("m","没有id");
				return map;
			}
			List list=(ArrayList)ids;
			if (ObjectUtil.isEmptyAll(list)){
				map.put("m","没有id!");
				return map;
			}
			n=list.size();
		}else {
			n=1;
		}
		List list=((ArrayList)param.get("idList"));
		int i=roleDao.updateState(param);
		String m="您选择了"+n+"条记录,成功了"+i+"条";
		map.put("m",m);

		return map;
	}

	@Override
	public Boolean delRole(HashMap record) {
		int ruNumber = roleDao.countRoleUser(record);
		Asserts.assertTrue(ruNumber==0,"该角色已经有用户在使用，不能删除");
		roleDao.delRoleMenu(record);
		roleDao.delRole(record);
		return true;
		
	}

	@Override
	public Boolean updateRole(HashMap param) {
		List<String> error=new ArrayList<String>();
		Role info = null;
		try {
			info = (Role) MapUtil.mapToObject(param, Role.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(info.getId()==null){
			error.add("操作失败!");
			param.put("errList", error);
			return false;
		}
		param.remove("ID_");
	//	Page page=roleDao.getRoles(param);
		
		info.setName(param.get("ROLENAME").toString());
		info.setCode(null == param.get("ROLECODE") ? "" : param.get("ROLECODE").toString());
		info.setCreateRemark(null == param.get("REMARK")? "" : param.get("REMARK").toString());
		if (!StringUtils.isEmpty(info.getCreateRemark())&&info.getCreateRemark().length()>50){
			return false;
		}
		roleDao.updateRole(info);
		return true;
	}

	@Override
	public Boolean updateMenu(HashMap param) {
		List<String> error=new ArrayList<String>();
		Menu info = null;
		try {
			info = (Menu) MapUtil.mapToObject(param, Menu.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(info.getId()==null){
			error.add("操作失败!");
			param.put("errList", error);
			return false;
		}
		//param.remove("ID_");
		//Page page=roleDao.getMenus(param);

		//info.setName((String)param.get("MENUNAME"));
		if (org.apache.commons.lang.math.NumberUtils.isNumber((String)param.get("SORT"))){
			info.setSort(Short.parseShort((String)param.get("SORT")) );
		}
		info.setShowName((String)param.get("MENUNAME"));
		//info.setId((String)param.get("ID_"));

		info.setCreateRemark((String)param.get("CREATE_REMARK"));
		//info.setCode((String)param.get("MENUCODE"));
		//info.setImgUrl((String)param.get("IMGURL"));
		info.setUpdateRemark(info.getUpdateRemark());
		if (org.apache.commons.lang.StringUtils.isBlank(info.getId())){
			return false;
		}
		 roleDao.updateMenu(info);
		return true;
	}




	@Override
	public boolean updateMenuState(HashMap map) {
		return roleDao.updateMenuState(map);
	}

	@Override
	public void unauthorizedRole(String id,String[] data) {
			int i = 0;
			//删除该用户所属的原来的用户组
			i = roleDao.deleteAuthorize(id);
			for (String userGroupId : data) {
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("id", UUID.randomUUID().toString().replace("-", ""));
				map.put("roleId", id);
				map.put("userGroupId", userGroupId);
				roleDao.unauthorizedRole(map);
				i++;
			}
			return;
		}

	@Override
	public List<String> queryMenuIdByRoleId(String roleId){
		return roleDao.getMenuId(roleId);
	}

	@Override
	public Map<String, Object> putqx(String id,String name) {
		int count = 0;
		Map<String, Object> map = new HashMap<String, Object>();
		if (org.apache.commons.lang.StringUtils.isNotBlank(name)){
			map.put("name",name);
		}
		List allMenu = roleDao.getAllMenus(map);
		map.put("allMenu", allMenu);
		if(!StringUtils.isEmpty(id)){
			//该组配置的用户
			List<String> menu = roleDao.getMenuId(id);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < menu.size(); i++) {
				if (i == menu.size() - 1) {
					sb.append(menu.get(i));
				} else {
					sb.append(menu.get(i)).append(",");
				}
				count ++ ;
			}
			map.put("menu", sb.toString());
		}
		map.put("count", count);
		return map;
	}

	@Override
	public void unauthorizedRole(Map<String, Object> map) {

	}

	@Override
	public Boolean insertSelective(HashMap param) {
		return null;
	}

	@Override
	public void saveunauthorized(Map map) {
		roleDao.deleteAuthorize((String)map.get("roleId"));
		if(map.get("menuIdList") != null)
		{
			List list=(List) map.get("menuIdList");
			if (ObjectUtil.isEmptyAll(list)){
				return;
			}
			Map m=null;
			for(int i=0; i<list.size();i++)
			{
				m=new HashMap();
				m.put("menuId", list.get(i));
				m.put("ID_", CommonUtil.getUUID());
				m.put("roleId", map.get("roleId"));
				roleDao.saveunauthorized(m);
			}
		}else if (map.get("menuId")!=null){
			if (org.apache.commons.lang.StringUtils.isNotBlank(((String)map.get("menuId")))){
				map.put("ID_", CommonUtil.getUUID());
				roleDao.saveunauthorized(map);
			}

		}
		
		
		
	}




}
